package com.aiyige.page.login.model.impl;

import com.aiyige.MyApp;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.jpush.TagAliasOperatorHelper;
import com.aiyige.model.Oauth2Register;
import com.aiyige.model.User;
import com.aiyige.model.request.RequestBindThirdAndSetPasswordBody;
import com.aiyige.model.request.RequestThirdOauthBackup;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.login.callbacks.IRegisterCallBack;
import com.aiyige.page.login.model.ISetPasswordModel;
import com.aiyige.page.login.view.ISetPasswordView;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ToastX;
import com.vondear.rxtools.RxTool;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SetPasswordImplement implements ISetPasswordModel {
    ISetPasswordView view;
    public static final String TAG = SetPasswordImplement.class.getSimpleName();

    @Override
    public void setPassword(String code, String mobile, String passWord, final IRegisterCallBack iRegisterCallBack) {
        view.showLoading();
        ApiManager.getService().oauth2Register(code, new Oauth2Register(mobile, RxTool.Md5(passWord))).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                view.hideLoading();
                try {
                    if (response.isSuccessful()) {
                        User user = JsonUtil.toObject(response.body().string(), User.class);
                        user = new User(user);
                        AccountUtil.updateCurrentUser(user);
                        TagAliasOperatorHelper.getInstance().registerLoginTagAndAlias(MyApp.getAppContext(), user);
                        iRegisterCallBack.success(user);
                    } else {
                        ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                        onFailure(call, new Throwable(data.getMessage()));
                    }

                } catch (Exception e) {
                    onFailure(call, new Throwable(e.toString()));
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                view.hideLoading();
                if (t != null) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }

    @Override
    public void bindPhoneAndPassword(String code, String mobile, String passWord, final User.ThirdOauthBackup third, final IRegisterCallBack iRegisterCallBack) {
        RequestThirdOauthBackup requestThirdOauthBackup = null;
        if (third != null) {
            requestThirdOauthBackup = RequestThirdOauthBackup.newBuilder()
                    .accessToken(third.getAccessToken())
                    .accessTokenExpire(third.getAccessTokenExpire()+"")
                    .avatar(third.getAvatar())
                    .nickName(third.getNickName())
                    .openid(third.getOpenid())
                    .source(third.getSource())
                    .uid(third.getUid())
                    .unionid(third.getUnionid())
                    .refreshToken(third.getRefreshToken())
                    .refreshTokenExpire(third.getRefreshTokenExpire()+"")
                    .build();
        }
        
        RequestBindThirdAndSetPasswordBody request = RequestBindThirdAndSetPasswordBody.newBuilder()
                .mobile(mobile)
                .password(RxTool.Md5(passWord))
                .thirdOauthBackup(requestThirdOauthBackup)
                .build();
        view.showLoading();
        ApiManager.getService().bindPhoneAndSetPassword(code, request).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                view.hideLoading();
                try {
                    if (response.isSuccessful()) {
                        User tempUser = JsonUtil.toObject(response.body().string(), User.class);
                        User user;
                        if (third != null) {
                            user = new User(tempUser);
                        } else {
                            user = AccountUtil.getCurrentUser();
                            user.setMobile(tempUser.getMobile());
                            user.setMobileVerified(user.getMobileVerified());
                        }
                        AccountUtil.updateCurrentUser(user);
                        TagAliasOperatorHelper.getInstance().registerLoginTagAndAlias(MyApp.getAppContext(), user);
                        iRegisterCallBack.success(user);
                    } else {
                        ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                        onFailure(call, new Throwable(data.getMessage()));
                    }

                } catch (Exception e) {
                    onFailure(call, new Throwable(e.toString()));
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                view.hideLoading();
                if (t != null) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }

    @Override
    public void setView(ISetPasswordView view) {
        this.view = view;
    }

}
